package com.dev.ac.util;

import org.apache.poi.xwpf.usermodel.*;

import java.util.List;

/**
 * @Author 付
 * @Date 2024-04-19 17:03
 * @Version 1.0
 * @description
 * @since 1.0
 */
public class XWPFDocumentUtils {

	public static void copyXWPFDocumentContent(XWPFDocument sourceDocument, XWPFDocument targetDocument) {
		// 复制段落
		List<XWPFParagraph> paragraphs = sourceDocument.getParagraphs();
		for (XWPFParagraph paragraph : paragraphs) {
			XWPFParagraph newParagraph = targetDocument.createParagraph();
			copyParagraphContent(paragraph, newParagraph);
		}
		// 复制表格
		List<XWPFTable> tables = sourceDocument.getTables();
		for (XWPFTable table : tables) {
			XWPFTable newTable = targetDocument.createTable();
			copyTableContent(table, newTable);
		}

		// 如果需要，可以添加更多复制其他类型元素的方法
	}

	private static void copyParagraphContent(XWPFParagraph source, XWPFParagraph target) {
		target.setAlignment(source.getAlignment());
		target.setIndentationFirstLine(source.getIndentationFirstLine());
		target.setIndentationHanging(source.getIndentationHanging());
		target.setSpacingAfter(source.getSpacingAfter());
		target.setSpacingBefore(source.getSpacingBefore());
		target.setSpacingLineRule(source.getSpacingLineRule());
		List<XWPFRun> runs = source.getRuns();
		for (XWPFRun run : runs) {
			XWPFRun newRun = target.createRun();
			newRun.setText(run.getText(0));
			newRun.setFontSize(10);
			newRun.setBold(run.isBold());
			newRun.setColor(run.getColor());
			newRun.setItalic(run.isItalic());
			// 复制其他属性...
		}
	}

	private static void copyTableContent(XWPFTable sourceTable, XWPFTable targetTable) {
		// 获取源表格的行数
		int numRows = sourceTable.getNumberOfRows();

		// 遍历源表格的每一行
		for (int i = 0; i < numRows; i++) {
			XWPFTableRow sourceRow = sourceTable.getRow(i);
			XWPFTableRow targetRow = targetTable.createRow(); // 创建目标行

			// 获取源行的单元格数
			int numCells = sourceRow.getTableCells().size();

			// 遍历源行的每个单元格
			for (int j = 0; j < numCells; j++) {
				XWPFTableCell sourceCell = sourceRow.getCell(j);
				// 创建目标单元格
				XWPFTableCell targetCell = targetRow.addNewTableCell();

				// 复制单元格内容，这里假设单元格只包含一个段落
				XWPFParagraph sourceParagraph = sourceCell.getParagraphArray(0);
				XWPFParagraph targetParagraph = targetCell.getParagraphArray(0);
				if (targetParagraph == null) {
					targetParagraph = targetCell.getXWPFDocument().createParagraph();
				}
				// 复制段落内容
				copyParagraphContent(sourceParagraph, targetParagraph);
			}
		}
	}
}